﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gin.Transactions;

namespace Gin.Commands
{
    public class TransactionContainer: Command, IContainerCommand
    {

        [GinArgumentText(Multiline = false, MaxLength = 500)]
        public string TransactionName { get; set; }

        [GinArgumentCommand(AllowMultiple = false)]
        public TransactionalCommand Command { get; set; }

        public override void Do(ExecutionContext context)
        {

            Transaction transaction = new Transaction()
            {
                TransactionName = TransactionName,
                TransactionState = TransactionState.Undefined
            };

            try
            {
                context.ExecutedPackage.AddTransaction(transaction);
                Command.Do(context, transaction);
                transaction.TransactionState = TransactionState.Active;
            }
            catch
            {
                transaction.Rollback();
            }
            finally
            {
                transaction.Save(context);
            }
        }

        public IEnumerable<Command> InnerCommands
        {
            get
            {
                return new List<Command>() 
                {
                    Command
                };
            }
        }

    }
}
